<template>
  <div class="main-box" :body-style="{ paddingBottom: '0' }">
    <OrgTree ref="orgTreeRef" @node-click="nodeClick" @back-org="backOrgData" />
    <div class="table-box">
      <ProTable ref="proTableRef" title="用户列表" :columns="columns" :requestApi="userApi.page" :initParam="queryParams"
        :dataCallback="dataCallback">
        <template #tableHeader>
          <el-button size="default" type="success" class="ml10" @click="openAddUser()" v-auth="'system:user:add'">
            <el-icon><ele-CirclePlus /></el-icon>{{ $t('message.userOperation.add') }}
          </el-button>
          <el-button type="primary" plain @click="batchAdd" size="default" v-auth="'system:user:add'"> 
            <el-icon><ele-Upload /></el-icon>{{ $t('message.commonBtn.batchImport') }} </el-button>
        </template>
        <template #operation="scope">
          <el-button icon="ele-Edit" size="small" text type="primary" @click="openEditUser(scope.row)"
            v-auth="'system:user:update'">
            {{ $t('message.userOperation.edit') }}
          </el-button>
          <el-dropdown>
            <span class="el-dropdown-link">
              <el-button text size="small" type="primary" icon="ele-ArrowDownBold">{{ $t('message.commonInfo.more') }}
              </el-button>
            </span>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item icon="ele-Lock" @click="grantRole(scope.row)" :disabled="!auth('system:user:grantRole')">
                  {{ $t('message.userOperation.grantRole') }}
                </el-dropdown-item>
                <el-dropdown-item icon="ele-RefreshLeft" @click="resetUserPwd(scope.row)"
                  :disabled="!auth('system:user:resetPassword')">
                  {{ $t('message.userOperation.resetPassword') }}
                </el-dropdown-item>
                <el-dropdown-item icon="ele-Delete" @click="delUser(scope.row)" divided
                  :disabled="!auth('system:user:delete')">
                  {{ $t('message.userOperation.delete') }}
                </el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </template>
      </ProTable>
      <EditUser ref="editUserRef" :title="state.editUserTitle" :orgData="state.orgTreeData" :genderData="state.genderData"
        @refresh="handleQuery" />
      <GrantRole ref="grantRoleRef" />
      <ImportExcel ref="importExcelRef"/>
    </div>
  </div>
</template>

<script lang="tsx" setup name="systemUser">
import { reactive, ref, defineAsyncComponent, watchEffect} from "vue";
import { ElMessageBox, ElMessage } from "element-plus";
import { auth } from "/@/utils/authFunction";
import { feature } from "/@/utils/axios-utils";
import { SysUser, SysOrg, SysDictData } from "/@/api-services/models/system";
import { useI18n } from 'vue-i18n';
import { formatDate } from "/@/utils/formatTime";
import { CheckIsNotNullOrEmpty } from "/@/utils/util";
import userApi from '/@/api-services/apis/system/userApi';
import dictDataApi from '/@/api-services/apis/system/dictDataApi';
import ProTable from '/@/components/ProTable/index.vue';
import { ColumnProps } from "/@/components/ProTable/interface";
const OrgTree = defineAsyncComponent(() => import('/@/views/system/org/component/orgTree.vue'));
const EditUser = defineAsyncComponent(() => import('/@/views/system/user/component/editUser.vue'));
const GrantRole = defineAsyncComponent(() => import('/@/views/system/user/component/grantRole.vue'));
const ImportExcel = defineAsyncComponent(() => import('/@/components/ImportExcel/index.vue'));
// 定义变量内容
const { t } = useI18n();
const proTableRef = ref();
const orgTreeRef = ref<InstanceType<typeof OrgTree>>();
const editUserRef = ref<InstanceType<typeof EditUser>>();
const grantRoleRef = ref<InstanceType<typeof GrantRole>>();
const queryParams = reactive({
  orgId: -1,
})
const state = reactive({
  loading: false,
  userData: [] as Array<SysUser>,
  orgTreeData: [] as Array<SysOrg>,
  editUserTitle: "",
  genderData: [] as Array<SysDictData>,//字典数据	
});



const dataCallback = (queryRes: any) => {
  var data = queryRes.data;
  return {
    items: data.items,
    totalCount: data.totalCount,
    pageIndex: data.pageIndex,
    pageSize: data.pageSize
  };
};


const columns: ColumnProps<SysUser>[] = [
  { prop: "account", label: t('message.sysUser.account') },
  {
    prop: "name", label: t('message.sysUser.name'),
    search: { el: "input", props: { placeholder: "请输入用户名称" } }
  },
  { prop: "orgName", label: t('message.sysUser.organization') },
  { prop: "posName", label: t('message.sysUser.position') },
  {
    prop: "birthday", label: t('message.sysUser.birthday'),
    render: scope => {
      if (CheckIsNotNullOrEmpty(scope.row.birthday)) {
        return formatDate(scope.row.birthday as Date, 'yyyy-MM-dd')
      }
      else{
        return "--"
      }
    }
  },
  {
    prop: "status",
    label: t('message.sysUser.status'),
    render: scope => {
      return (
        <el-switch
          v-auth="system:user:changeStatus"
          model-value={scope.row.status}
          active-text={scope.row.status ? t('message.userOperation.enable') : t('message.userOperation.disable')}
          active-value="enable"
          inactive-value="disable"
          onClick={() => changeStatus(scope.row)}
        />
      );
    }
  },
  {
    prop: "gender", label: t('message.sysUser.gender'),
    render: scope => {
      var data = state.genderData.filter(item => item.value == scope.row.gender)[0]
      return (<el-tag size={data.tagSize} type={data.tagType}> {data.name}</el-tag>)
    }
  },
  { prop: "operation", label: t('message.userOperation.oper'), fixed: "right" }
]
// 查询操作
const handleQuery = async () => {
  proTableRef.value.getTableList()
};
const queryGenderType = async () => {
  var res = await dictDataApi.getDatalistByType("Gender")
  state.genderData = res.data.data ?? []
}

watchEffect(async () => {
  queryGenderType();
});

// 树组件点击
const nodeClick = async (node: any) => {
  queryParams.orgId = node.id;
  handleQuery();
};

//获取子组件传递的组织数据
const backOrgData = (orgData: any) => {
  state.orgTreeData = orgData
}

// 打开新增页面
function openAddUser() {
  state.editUserTitle = t('message.userOperation.addUser');
  editUserRef.value?.openDialog({});
}

// 打开编辑页面
const openEditUser = (row: any) => {
  state.editUserTitle = t('message.userOperation.editUser');
  editUserRef.value?.openDialog(row);
};

// 删除
const delUser = (row: any) => {
  ElMessageBox.confirm(`${t('message.userAlter.isDeleteUser')}【${row.account}】?`, t('message.userAlter.alter'), {
    confirmButtonText: t('message.userAlter.confirm'),
    cancelButtonText: t('message.userAlter.cancel'),
    type: "warning",
  })
    .then(async () => {
      var ids = [{ id: row.id }]
      const [err] = await feature(userApi.delete(ids));
      if (err) {
        ElMessage.error(err.message)
      }else{
        handleQuery();
        ElMessage.success(t('message.userAlter.deleteSuccess'));
      }      
    })
    .catch(() => { });
};
// 修改状态
const changeStatus = async (row: any) => {
  var status = row.status;
  var mes: string;
  if (status === "enable") {
    mes = `${t('message.userAlter.disableUser')}【${row.account}】`
  }
  else {
    mes = `${t('message.userAlter.enableUser')}【${row.account}】`
  }
  ElMessageBox.confirm(mes, t('message.userAlter.alter'), {
    confirmButtonText: t('message.userAlter.confirm'),
    cancelButtonText: t('message.userAlter.cancel'),
    type: "warning",
  })
    .then(async () => {
      const [err] = await feature(userApi.changeStatus({ id: row.id }));
      if (err) {
        ElMessage.error(err.message)
      } else {
        row.status= status==="enable"?"disable":"enable";
        //handleQuery();
      }
    })
    //取消动作
    .catch(() => {
    });

};

// 重置密码
const resetUserPwd = async (row: any) => {
  ElMessageBox.confirm(`${t('message.userAlter.isResetPassword')}'【${row.account}】?`, t('message.userAlter.alter'), {
    confirmButtonText: t('message.userAlter.confirm'),
    cancelButtonText: t('message.userAlter.cancel'),
    type: "warning",
  })
    .then(async () => {
      await userApi.resetPassword({ id: row.id });
      ElMessage.success(t('message.userAlter.resetSuccess'));
    })
    .catch(() => { });
};
const grantRole = (row: any) => {
  grantRoleRef.value?.openDialog(row)
}

// 批量添加用户
const importExcelRef = ref<InstanceType<typeof ImportExcel>>();//ref<InstanceType<typeof ImportExcel> | null>(null);
const batchAdd = () => {
  const params = {
    title: "用户",
    tempApi: userApi.templateDownload,
    importApi: userApi.batchImport,
    //getTableList: proTable.value?.getTableList
    errorDownloadApi: userApi.errorFileDownload
  };
  importExcelRef.value?.acceptParams(params);
};
</script>
